<?php
/**
 * 日志管理类
 */
class Logger
{
    private $logDir;
    private $logFile;
    private $logLevel;
    private $levelPriority = [
        'DEBUG' => 0,
        'INFO' => 1,
        'WARNING' => 2,
        'ERROR' => 3
    ];
    
    public function __construct($config = null)
    {
        $this->logDir = __DIR__ . '/../logs';
        
        // 创建日志目录
        if (!is_dir($this->logDir)) {
            mkdir($this->logDir, 0755, true);
        }
        
        // 按日期创建日志文件
        $this->logFile = $this->logDir . '/app_' . date('Y-m-d') . '.log';
        
        // 设置日志级别（从配置文件读取，默认为debug）
        if ($config && isset($config['log_level'])) {
            $this->logLevel = strtoupper($config['log_level']);
        } else {
            $this->logLevel = 'DEBUG';
        }
    }
    
    /**
     * 写入日志
     * @param string $level 日志级别 (INFO, ERROR, DEBUG, WARNING)
     * @param string $message 日志消息
     * @param array $context 上下文数据
     */
    public function log($level, $message, $context = [])
    {
        // 检查当前日志级别是否应该被记录
        if (!$this->shouldLog($level)) {
            return;
        }
        
        $timestamp = date('Y-m-d H:i:s');
        $contextStr = !empty($context) ? ' | ' . json_encode($context, JSON_UNESCAPED_UNICODE) : '';
        $logMessage = "[{$timestamp}] [{$level}] {$message}{$contextStr}" . PHP_EOL;
        
        file_put_contents($this->logFile, $logMessage, FILE_APPEND);
    }
    
    /**
     * 判断是否应该记录该级别的日志
     * @param string $level
     * @return bool
     */
    private function shouldLog($level)
    {
        $currentPriority = $this->levelPriority[$this->logLevel] ?? 0;
        $messagePriority = $this->levelPriority[$level] ?? 0;
        
        return $messagePriority >= $currentPriority;
    }
    
    public function info($message, $context = [])
    {
        $this->log('INFO', $message, $context);
    }
    
    public function error($message, $context = [])
    {
        $this->log('ERROR', $message, $context);
    }
    
    public function debug($message, $context = [])
    {
        $this->log('DEBUG', $message, $context);
    }
    
    public function warning($message, $context = [])
    {
        $this->log('WARNING', $message, $context);
    }
    
    /**
     * 获取今天的日志内容
     * @return string
     */
    public function getTodayLog()
    {
        if (file_exists($this->logFile)) {
            return file_get_contents($this->logFile);
        }
        return '';
    }
    
    /**
     * 清空今天的日志
     */
    public function clearTodayLog()
    {
        if (file_exists($this->logFile)) {
            file_put_contents($this->logFile, '');
        }
    }
}
